package com.witframework.core.persistence.hibernate;

import java.io.File;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.hibernate.MappingException;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.util.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WitAnnotationConfiguration extends AnnotationConfiguration {
	private Logger log = LoggerFactory.getLogger( WitAnnotationConfiguration.class );
	@Override
	protected void parseMappingElement(Element subelement, String name) {
		Attribute rsrc = subelement.attribute( "resource" );
		Attribute file = subelement.attribute( "file" );
		Attribute jar = subelement.attribute( "jar" );
		Attribute pckg = subelement.attribute( "package" );
		Attribute clazz = subelement.attribute( "class" );
		if ( rsrc != null ) {
			log.debug( "{} <- {}", name, rsrc );
			addResource( rsrc.getValue() );
		}
		else if ( jar != null ) {
			log.debug( "{} <- {}", name, jar );
			addJar( new File( jar.getValue() ) );
		}
		else if ( file != null ) {
			log.debug(  "{} <- {}", name, file );
			addFile( file.getValue() );
		}
		else if ( pckg != null ) {
			log.debug(  "{} <- {}", name, pckg );
			addPackage( pckg.getValue() );
		}
		else if ( clazz != null ) {
			log.debug(  "{} <- {}", name, clazz );
			Class loadedClass=null;
			try {
				loadedClass = ReflectHelper.classForName( clazz.getValue() );
			}
			catch (Exception cnf) {
//				throw new MappingException(
//						"Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:",
//						cnf
//				);
				log.error(
						"Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:"
						,cnf);
			}			
			if(loadedClass!=null)
				addAnnotatedClass( loadedClass );
		}
		else {
			throw new MappingException( "<mapping> element in configuration specifies no attributes" );
		}
	}

	
}

